<!--
/************************************************************************/
/*																		*/
/*	index.htm - Main page for WiH2O opensource wifi-enable lawn		*/
/*		sprinkler controller application for chipKIT PIC32 				*/
/*		microcontroller boards											*/
/*																		*/
/************************************************************************/
/*	Author: 	Andy Coulson											*/
/*	Copyright 2013, Practical Apps, LLC									*/
/************************************************************************/
-->
<html>
	<head>
		<title>W&#299;H2O</title>
		<link rel="stylesheet" type="text/css" href="main.css">
		<link rel="stylesheet" type="text/css" href="jqui.css">
		<link rel="stylesheet" type="text/css" href="jquithem.css">
		<link rel="stylesheet" type="text/css" href="jquidp.css">
		<meta http-equiv="refresh" content="900"><!--refresh every 15 min-->
		<script src="jqrymin.js"></script>
		<script src="jquimin.js"></script>
		<script src="jsrender.js"></script>
	</head>
	<body>
	
		<div class="main">
			<div class="banner">
				<div class="heading">W&#299;H2O <img src="spinner1.gif" id="loading" style="display:none"/></div>
				<div class="timestamp">
					<div id="date">mm/dd/yy</div>
					<div id="time">hh:mm</div>
					<div id="timePopup">
						<div style="height:20px">
							<div id="validateTips" class="ui-state-highlight" style="display:none;">&nbsp;</div>
						</div>
						<label>New Time:</label><input id="txtTime" type="text" size="5" maxlength="5" value="xx:xx"/><br/><br/>
						<button id="timeSubmit">Submit</button>
						<button id="timeCancel">Cancel</button>
					</div>
					<div id="datePopup">
						<div style="height:20px">
							<div id="validateTips" class="ui-state-highlight" style="display:none;">&nbsp;</div>
						</div>
						<label>New Date:</label><input id="txtDate" type="text" size="8" maxlength="8" value="xx:xx:xx"/><br/><br/>
						<button id="dateSubmit">Submit</button>
						<button id="dateCancel">Cancel</button>
					</div>
				</div>
			</div>
			<div class="schedule">
				<div style="height:20px; vertical-align: top;">Status: <span id="status">pending...<span/></div>
				<div>
					&nbsp;&nbsp;
					<img src="start24.png" alt="Run Program" id="pgmStart"/>
					&nbsp;&nbsp;&nbsp;
					<img src="pause24.png" alt="Stop Program" id="pgmStop"/>
				</div>
				
				<table border="0" cellpadding="1" cellspacing="1">
					<thead>
						<tr>
							<th align="left">Event Description</th>
							<th>Zone Num</th>
							<th>Start Time</th>
							<th>Run Time</th>
							<th>Sun</th>
							<th>Mon</th>
							<th>Tues</th>
							<th>Wed</th>
							<th>Thur</th>
							<th>Fri</th>
							<th>Sat</th>
							<th></th>
							<th colspan="2">Manual</br>Action</th>
							<th width="75px">Last Ran</th>
						</tr>
					</thead>
					<tbody id="eventTable">
						<tr>
							<td>
								<input name="eventIdx" type="hidden" value="0" />
								<input maxlength="32" name="zoneName" size="32" type="text" value="-unspecified-" />
							</td>
							<td>
								<select name="zoneNumber" size="1"><option selected="selected" value="">off</option><option value="1">1</option><option value="2">2</option><option value="3">3</option></select></td>
							<td>
								<input maxlength="5" name="zoneStart" size="5" type="text" value="12:00" /></td>
							<td>
								<input maxlength="2" name="zoneRuntime" size="2" type="text" value="0" /></td>
							<td>
								<input name="zoneSunday" type="checkbox" value="1" /></td>
							<td>
								<input name="zoneMonday" type="checkbox" value="1" /></td>
							<td>
								<input name="zoneTuesday" type="checkbox" value="1" /></td>
							<td>
								<input name="zoneWednesday" type="checkbox" value="1" /></td>
							<td>
								<input name="zoneThursday" type="checkbox" value="1" /></td>
							<td>
								<input name="zoneFriday" type="checkbox" value="1" /></td>
							<td>
								<input name="zoneSaturday" type="checkbox" value="1" /></td>
							<td>
								<input alt="Save" id="zoneSave_1" type="submit" value="Save"/></td>
							<td>
								<img alt="Zone 1 On" name="zoneOn" src="on24.png" style="width: 24px; height: 24px;"/></td>
							<td>
								<img alt="Zone 1 Off" name="zoneOff" src="off24.png" style="width: 24px; height: 24px;"/></td>
							<td class="lastStart" NOWRAP>
							</td>
						</tr>
					</tbody>
				</table>
				<br/>
			</div>
		</div>
		
	</body>
	
	<script id="eventTmpl" type="text/x-jsrender">
		{{for events}}
		<tr>
			<td>
				<input name="eventIdx" type="hidden" value="{{>eventIdx}}" />
				<input maxlength="32" name="eventName" size="36" type="text" value="{{>eventName}}" />
			</td>
			<td>
				<select name="zoneNumber" size="1" id="zoneNumber_{{>eventIdx}}">
				</select>
			</td>
			<td>
				<input maxlength="5" name="eventStart" size="5" type="text" value="{{>eventTime}}" id="zoneTime_{{>eventIdx}}"/>
			</td>
			<td>
				<input maxlength="2" name="eventRuntime" size="2" type="text" value="{{>eventRuntime}}" /></td>
			<td>
				<input name="eventSun" type="checkbox" {{checker:eventRunOn day='Sunday'}} value="Y" /></td>
			<td>
				<input name="eventMon" type="checkbox" {{checker:eventRunOn day='Monday'}} value="Y" /></td>
			<td>
				<input name="eventTues" type="checkbox" {{checker:eventRunOn day='Tuesday'}} value="Y" /></td>
			<td>
				<input name="eventWed" type="checkbox" {{checker:eventRunOn day='Wednesday'}} value="Y" /></td>
			<td>
				<input name="eventThurs" type="checkbox" {{checker:eventRunOn day='Thursday'}} value="Y" /></td>
			<td>
				<input name="eventFri" type="checkbox" {{checker:eventRunOn day='Friday'}} value="Y" /></td>
			<td>
				<input name="eventSat" type="checkbox" {{checker:eventRunOn day='Saturday'}} value="Y" /></td>
			<td>
				<input alt="Save" type="submit" value="Save"/></td>
			<td>
				<img alt="Zone {{>eventIdx}} On" name="zoneOn" src="on24.png" style="width: 24px; height: 24px;"/></td>
			<td>
				<img alt="Zone {{>eventIdx}} Off" name="zoneOff" src="off24.png" style="width: 24px; height: 24px;"/></td>
			<td NOWRAP>
				<div name="lastStart" class="lastStart" >{{dateTime:lastStart}}</div>
			</td>
		</tr>
		{{/for}}
	</script>

	<script type="text/javascript">
	//var jsondata = {"maxZones": 6, "events": [{"eventIdx": 0, "eventName: 'NAME_1_xxxxxxxxxxxxxxxxxxxxx321|', zoneNumber: 1, eventActive: 'Y', eventTime: '19:30', eventRuntime: 10, eventRunOn: 'YNYNYNN'}]};

	$(function () {	
		$.ajaxSetup({ cache: false, contentType:"application/json; charset=utf-8" });
		
		$(document).ajaxStart(function() {
			$("#loading").show();
		});
		$(document).ajaxComplete(function() {
			$("#loading").hide();
		});
	
		// Custom converters for use by JsRender template rendering
		$.views.converters({
			checker: function (value) {
				var result = "";
				var testDay = this.tagCtx.props.day;
				if (
					(testDay == "Sunday" && value.substr(0,1) == "Y")
					|| (testDay == "Monday" && value.substr(1,1) == "Y")
					|| (testDay == "Tuesday" && value.substr(2,1) == "Y")
					|| (testDay == "Wednesday" && value.substr(3,1) == "Y")
					|| (testDay == "Thursday" && value.substr(4,1) == "Y")
					|| (testDay == "Friday" && value.substr(5,1) == "Y")
					|| (testDay == "Saturday" && value.substr(6,1) == "Y")
				) {
					result = "CHECKED = 'CHECKED'";
				}
				return result;
			},
			dateTime: function (value) {
				var result = "";
				if (value > 0) {
					var dt = new Date(value * 1000);
					var sTime = (dt.getUTCHours() < 10) ? ("0" + dt.getUTCHours()) : dt.getUTCHours();
					sTime = sTime + ":" + ((dt.getUTCMinutes() < 10) ? ("0" + dt.getUTCMinutes()) : dt.getUTCMinutes());
					var sDate = (dt.getUTCMonth()+1) + "/" + dt.getUTCDate();
					result = sDate + " " + sTime;
				}
				return result;
			}
		});
		
		// We user JsRender to render the template defined by 'eventTmpl', above
		$.getJSON('getevnts.do').done(function( jsondata ) {
			//jsondata.zoneArray = zoneArray;
			$("#eventTable").html(
				$("#eventTmpl").render(jsondata)
			);
			var zonecount = jsondata.maxZones;
			var ary = document.getElementsByName("zoneNumber");
			// Loop over SELECT controls
			for (j = 0; j < ary.length; j++) { 
				var theSelect = $("#zoneNumber_" + j);
				for (i = 0; i <= zonecount; i++) {	// add {zonecount} options to each select
					if (i == 0)
						optVal = 'off';
					else
						optVal = i;
					if (jsondata.events[j].zoneNumber == i ) {
						theSelect.append("<option value='" + optVal + "' SELECTED='SELECTED'>" + optVal + "</option>");
					} else {
						theSelect.append("<option value='" + optVal + "'>" + optVal + "</option>");
					}
					console.log( "Add option: " + optVal + ", " + j);
				}
			}
						
			$('INPUT[type="submit"]').click(function(event) {
				// trim spaces from Event name
				var nameField = $(this).parent().parent().find('input[name="eventName"]')[0]; // the eventName input field
				var nameStr = nameField.value;
				nameStr = nameStr.trim()
				nameField.value = nameStr;
				var inputFields = $(this).parent().parent().find('input,select');
				var params = inputFields.serialize();
				$.ajax({
					url: "saveevnt.do",
					type: "get",
					data: params,
					timeout: 5000,
					dataType: "text",
					success: function(data){},
					error:function(){
						alert("Failed to contact WiH20 controller");
					}   
				}); 
				return false;
			});	
				
			$("img[name='zoneOff']").click(function(event) {
				var parentForm = $(this).parent().parent();
				var z = parentForm.find("input[name='eventIdx']").val();
				$.ajax({
					url: "setzone.do",
					type: "get",
					data: { eventIdx: z, zoneState: 0 },
					timeout: 2000,
					success: function(){
						getStatus();
					},
					error:function(){
						alert("Failed to contact WiH20 controller");
					}   
				}); 
			});
			
			$("img[name='zoneOn']").click(function(event) {
				var parentForm = $(this).parent().parent();
				var z = parentForm.find("input[name='eventIdx']").val();
				$.ajax({
					url: "setzone.do",
					type: "get",
					data: { eventIdx: z, zoneState: 1 },
					timeout: 2000,
					success: function(){
						var dt = new Date();
						var sTime = (dt.getUTCHours() < 10) ? ("0" + dt.getUTCHours()) : dt.getUTCHours();
						sTime = sTime + ":" + ((dt.getUTCMinutes() < 10) ? ("0" + dt.getUTCMinutes()) : dt.getUTCMinutes());
						var sDate = (dt.getUTCMonth()+1) + "/" + dt.getUTCDate();
						parentForm.find(".lastStart").text(sDate + " " + sTime);
						getStatus();
					},
					error:function(){
						alert("Failed to contact W&#299;H20 controller");
					}   
				}); 
			});
		})
		.fail(function( jqxhr, textStatus, error ) {
			var err = textStatus + ', ' + error;
			console.log( "Request Failed: " + err);
			$("#status").html("Not Responding");
			$("#pgmStart").css({ opacity: 0.4 });
			$("#pgmStop").css({ opacity: 0.4 });
		});

		$("[id^='zoneTime_']").change( function(event) {
			$('#txtTime').val($('#time').text());
			var clickedId = '#' + this.id;
			if (checkRegexp( $(this), /^[0-2][0-9]:[0-5][0-9]$/, "Time must be in format hh:mm", $(".schedule") )) {
				$(this).removeClass( "ui-state-error" );
			}
		});

		$('#time').click( function() {
			$('#txtTime').val($('#time').text());
            loadPopupBox('#timePopup', '#time');
		});
		
		$('#timeSubmit').click( function() {
			sTime = $('#txtTime');
			if (checkRegexp( sTime, /^[0-2][0-9]:[0-5][0-9]$/, "Time must be in format hh:mm", sTime.parent() )) {
				$("#time").text(sTime.val());
				unloadPopupBox('#timePopup');
				sTime.removeClass( "ui-state-error" );
				tDate = $("#date").text();
				tTime = $("#time").text();
				$.ajax({
					url: "settime.do?date=" + tDate + "&time=" + tTime + ":00",
					type: "get",
					timeout: 5000,
					dataType: "text",
					success: function(data){},
					error:function(){
						alert("Failed to contact W&#299;H20 controller");
					}   
				}); 
			} else
				return false;
        });
		
		$('#timeCancel').click( function() {
			$('#txtTime').removeClass( "ui-state-error" );
            unloadPopupBox('#timePopup');
        });
		
		$( "#txtDate" ).datepicker({ dateFormat: "mm/dd/y" });
	
		$('#date').click( function() {
			$('#txtDate').val($('#date').text());
            loadPopupBox('#datePopup', '#date');
		});
		
		$('#dateSubmit').click( function() {
			sDate = $('#txtDate');
			if (checkRegexp( sDate, /^[0-1][0-9]\/[0-3][0-9]\/[0-9][0-9]$/, "Date must be in format mm/dd/yy", sDate.parent() )) {
				$("#date").text(sDate.val());
				unloadPopupBox('#datePopup');
				sDate.removeClass( "ui-state-error" );
				tDate = $("#date").text();
				tTime = $("#time").text();
				$.ajax({
					url: "settime.do?date=" + tDate + "&time=" + tTime + ":00",
					type: "get",
					timeout: 5000,
					dataType: "text",
					success: function(data){},
					error:function(){
						alert("Failed to contact W&#299;H20 controller");
					}   
				}); 
			} else
				return false;
        });
		
		$('#dateCancel').click( function() {
			$('#txtDate').removeClass( "ui-state-error" );
            unloadPopupBox('#datePopup');
        });

		function loadPopupBox(which, relativeTo) {    // To Load the Popupbox
            $(which).fadeIn("fast");
			$(which).position({
				my: 'center top',
				at: 'center top',
				of: relativeTo
			});
        }

		function unloadPopupBox(which) {    // TO Unload the Popupbox
            $(which).fadeOut("fast");
        }
		
		
		getStatus();
		
		setInterval(function(){getStatus()},10000);
	});
	
	$("#pgmStart").click(function(event) {
		if (!this.disabled) {
			$.ajax({
				url: "setsts.do",
				type: "get",
				data: { state: "Running" },
				timeout: 5000,
				success: function(){
					getStatus();
				},
				error:function(){
					alert("Failed to contact W&#299;H20 controller");
				}   
			}); 
		}
	});
	
	$("#pgmStop").click(function(event) {
		if (!this.disabled) {
			$.ajax({
				url: "setsts.do",
				type: "get",
				data: { state: "Paused" },
				timeout: 2000,
				success: function(){
					getStatus();
				},
				error:function(){
					alert("Failed to contact W&#299;H20 controller");
				}   
			}); 
		}
	});

	
	function updateTips(tipHolder, t ) {
		tips = tipHolder.find( "#validateTips" );
		tips.text( t ).fadeIn("fast");
		setTimeout(function() {
			tips.fadeOut("slow");
		}, 2000 );
	}
	
	function checkRegexp( o, regexp, n, tipHolder ) {
		if ( !( regexp.test( o.val() ) ) ) {
			o.addClass( "ui-state-error" );
			updateTips(tipHolder, n );
			return false;
		} else {
			return true;
		}
    }

	function getStatus() {
		$.getJSON("/getsts.do").done(function( json ) {
			$("#status").html(json.status);
			$("#date").html(json.date);
			$("#time").html(json.time.substring(0,5));
			if (json.status == "Running") {
				$("#pgmStart").css({ opacity: 0.4 }).prop('disabled', true);
				$("#pgmStop").css({ opacity: 1 }).prop('disabled', false);
			} else if (json.status == "Paused") {
				$("#pgmStart").css({ opacity: 1 }).prop('disabled', false);
				$("#pgmStop").css({ opacity: 0.4 }).prop('disabled', true);
			} else {
				$("#pgmStart").css({ opacity: 0.4 });
				$("#pgmStop").css({ opacity: 0.4 });
			}
		})
		.fail(function( jqxhr, textStatus, error ) {
			var err = textStatus + ', ' + error;
			console.log( "Request Failed: " + err);
			$("#status").html("W&#299;H20 not Responding");
			$("#pgmStart").css({ opacity: 0.4 });
			$("#pgmStop").css({ opacity: 0.4 });
		});
	}
	
	</script>
</html>
